package com.hjm.mall.service.impl;

import com.hjm.mall.dao.ImageMapper;
import com.hjm.mall.entity.Image;
import com.hjm.mall.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class ImageServiceImpl implements ImageService {
    @Autowired
    ImageMapper imageMapper;

    @Override
    public List<Image> findAllImage() {
        return imageMapper.findAllImage();
    }

    @Override
    public int insertImage(Image image) {
        return imageMapper.insertImage(image);
    }

    @Override
    public Image getImageById(int id) {
        return imageMapper.getImageById(id);
    }

    @Override
    public int updateImage(Image image) {
        return imageMapper.updateImage(image);
    }

    @Override
    public int delImage(Integer id) {
        return imageMapper.delImage(id);
    }

    public ResponseEntity<byte[]> prepareImageResponseEntity(Image image){
        // 希望返回图片内容作为HTTP响应体
        HttpHeaders headers = new HttpHeaders();
        String imageType = image.getType();
        if (imageType.equals("image/jpeg")) {
            headers.setContentType(MediaType.IMAGE_JPEG);
        } else if (imageType.equals("image/png")) {
            headers.setContentType(MediaType.IMAGE_PNG);
        } else if (imageType.equals("image/gif")) {
            headers.setContentType(MediaType.IMAGE_GIF);
        }

        return new ResponseEntity<>(image.getImage(), headers, HttpStatus.OK);
    }

    public Image prepImageSaveToDB(MultipartFile file){
        Image newImage = new Image();
        String imageType = file.getContentType();
        System.out.println("上传文件类型："+imageType);
        if (!(imageType != null && (imageType.equals("image/jpeg") || imageType.equals("image/png") || imageType.equals("image/gif"))))
            return null;
        try {
            byte[] image = file.getBytes();
            long timestampSeconds = System.currentTimeMillis() / 1000;
            String imageName = timestampSeconds + "_" + image.length;

            newImage.setImage(image);
            newImage.setImageName(imageName);
            newImage.setType(file.getContentType());

            return newImage;
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

}
